<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片式 -->
    <el-card>
      <!-- 消息框 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      
      <!-- 步骤条 -->
      <el-steps :active="active" finish-status="success" align-center style="margin-top: 15px">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成 "></el-step>
      </el-steps>

      <!-- 左侧、标签页 -->
      <el-form :model="goodsForm" label-position="top" style="margin-left: 15px"
           :rules="goodsFormRules" ref="goodsFormRef" label-width="80px" class="demo-goodsForm">
        <el-tabs v-model="activeTab" @tab-click="Tab" tab-position="left" style="margin: 15px" 
        :before-leave="beforeTabLeave">
          <!-- 步骤1 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称	" prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="goodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="goodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="goodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="分类列表" prop="goods_cat">
              <div class="block">
                <el-cascader expand-trigger="hover" :options="goodsCateList" placeholder="选择商品分类"
                v-model="selectKeys"  @change="selectGoodsChange" :props="goodsCateProps">
                </el-cascader>
              </div>
            </el-form-item>
          </el-tab-pane>
          <!-- 步骤2 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cb" v-for="(cb, i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 步骤3 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 步骤4 -->
          <!-- 上传图片要手动设置 token -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload" 
            :headers="headersObj" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <!-- 步骤5 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="goodsForm.goods_introduce"></quill-editor>
          </el-tab-pane>
          <!-- 步骤6 -->
          <el-tab-pane label="添加完成" name="5">
            <el-form-item label="商品名字">
              <el-input v-model="goodsForm.goods_name" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="商品价格">
              <el-input v-model="goodsForm.goods_price" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="商品数量">
              <el-input v-model="goodsForm.goods_number" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="商品重量">
              <el-input v-model="goodsForm.goods_weight" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-input v-model="goodsForm.goods_cat" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="商品介绍">
              <el-input v-model="goodsForm.goods_introduce" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="商品图片">
              <el-input v-model="goodsForm.pics" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="商品参数">
              <el-input v-model="goodsForm.attrs" :disabled="true"></el-input>
            </el-form-item>
            <el-button type="primary" @click="addGoods">添加完成</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="上传的图片" style="width:100%; height: 100%">
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      active: 0,
      activeTab: '0',
      goodsForm: {
        goods_name: '',
        goods_price: null,
        goods_number: null,
        goods_weight: null,
        goods_cat: '',
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      selectKeys: [],
      goodsCateList: [],
      goodsCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        childer: 'children',
      },
      // 上传图片请求设置请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      goodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 150, message: '商品名称长度在 1 到 150 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', message: '商品价格必须是数值型', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { type: 'number', message: '商品数量必须是数值型', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { type: 'number', message: '商品重量必须是数值型', trigger: 'blur' }
        ],
      }, 
      manyTableData: [],
      onlyTableData: [],
      previewPath: '',
      previewVisible: false,
    }
  },
  created() {
    this.getGoodsCate()
  },
  methods: {
    // 处理移除图片的操作
    handleRemove(file, fileList) {
      // 获取将要删除的图片的临时路径，从pics数组中查找并删除
      const filePath = file.response.data.tmp_path
      const i = this.goodsForm.pics.findIndex(x => x.pic === filePath)
      this.goodsForm.pics.splice(i, 1)
    },
    // 处理图片预览效果
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 图片上传成功事件
    handleSuccess(response) {
      console.log(response)
      this.goodsForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    getGoodsCate() {
      this.$http.get('categories').then(res => {
        this.goodsCateList = res.data.data
      })
    },
    selectGoodsChange() {
      if(this.selectKeys.length !== 3){
        // 说明选择的不是三级
        this.$message.error("请选择三级分类")
        this.selectKeys = []
      }else {
        // 是三级分类
        this.goodsForm.goods_cat = this.selectKeys.toString()
        console.log(this.selectKeys.toString())
      }
    },
    Tab() {
      this.active = parseInt(this.activeTab)
      if(this.activeTab === '1') {
        // 此时商品参数标签页
        this.$http.get(`categories/${this.selectKeys[2]}/attributes`, {
          params: {sel: 'many'}
        }).then(res => {
          res.data.data.forEach(item => {
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
          })
          this.manyTableData = res.data.data
          console.log(this.manyTableData)
        })
      }

      if(this.activeTab === '2') {
        // 此时访问的是商品属性标签页
        this.$http.get(`categories/${this.selectKeys[2]}/attributes`, {
          params: {sel: 'only'}
        }).then(res => {
          this.onlyTableData = res.data.data
          console.log(res.data)
        })
      }
      if(this.activeTab === '5') {
        // 处理attrs项  遍历manyTableData,onlyTableData
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.goodsForm.attrs.push(newInfo)
        })
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.goodsForm.attrs.push(newInfo)
        })
      }
    },
    beforeTabLeave(ActiveName, OldActiveName) {
      if(OldActiveName === '0' && this.selectKeys.length !== 3) {
        this.$message.error("请先选择商品分类")
        return false
      }
    },
    addGoods() {
      this.$refs.goodsFormRef.validate((valid) => {
        if (valid) {
          // 发起请求 添加商品
          this.$http.post('goods', this.goodsForm).then(res => {
            if(res.data.meta.status !== 201) {
              this.$message.error("创建失败: " + res.data.meta.msg)
            }else {
              this.$message.success("创建成功")
              this.$router.push('/goods')
            }
          })
        } else {
          this.$message.error("请填写必要的表单项(含*号的项)")
          return false;
        }
      });
    }
  },
}
</script>
<style lang="scss" scoped>
  .el-checkbox {
    margin: 0 5px 0 0 !important;
  }
  .ql-editor {
    height: 300px;
  }
</style>